package us.codecraft.webmagic.samples.tuchong;

import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TcExifResolveUtil {

	private static Pattern FOCALLEN_PATTERN = Pattern.compile("^([0-9]+)(\\.[0])?mm$");
	
	private static Pattern FNumber_PATTERN = Pattern.compile("f/([1-9][0-9]{0,2}\\.[0-9]{1,2})");

	private static Pattern ISO_PATTERN = Pattern.compile("^ISO([0-9]+)$");

	private static Pattern ExposurePattern = Pattern.compile("((1/)?[0-9]+)s");

	public static Date shootTime(String time) {
		try {
			if (time == null || time.length() == 0) {
				return null;
			}
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return dateFormat.parse(time);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Integer iso(String value) {
		try {
			if (StringUtils.isBlank(value)) {
				return null;
			}
			value = value.replaceAll("\\s*","");
			Matcher matcher = ISO_PATTERN.matcher(value);
			if (matcher.find()) {
				return Integer.valueOf(matcher.group(1));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Integer focalLen(String value) {
		// 41mm
		try {
			if (StringUtils.isBlank(value)) {
				return null;
			}
			value = value.replaceAll("\\s*","");
			Matcher matcher = FOCALLEN_PATTERN.matcher(value);
			if (matcher.find()) {
				return Integer.valueOf(matcher.group(1));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Float fNumber(String value) {
		// f/1.8
		try {
			if (StringUtils.isBlank(value)) {
				return null;
			}
			value = value.replaceAll("\\s*","");
			Matcher matcher = FNumber_PATTERN.matcher(value);
			if (matcher.find()) {
				return Float.valueOf(matcher.group(1));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String exposureTime(String value) {
		try {
			if (StringUtils.isBlank(value)) {
				return null;
			}
			value = value.replaceAll("\\s*","");
			Matcher matcher = ExposurePattern.matcher(value);
			if (matcher.find()) {
				return matcher.group(1);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
